var express = require("express");
var router = express.Router();
var url = require("url");
var user = require("../modules/user.js");

router.all("*", function(req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	res.header("X-Powered-By", ' 3.2.1');
	res.header("Content-Type", "application/json;charset=utf-8");
	next();
});
//注册接口
router.post("/adduser", function(req, res) {
	var username = req.body.username;
	var password = req.body.password;
	var apasswprd = req.body.apasswprd;
	var sql = "insert into user (username,password) values (?,?)";
	var arr = [username, password];
	user.add(sql, arr, function(result) {			
		if(result) {
			res.json(200, {
				"msg": "注册成功,请登录"
			})
		}else {
			res.json(200,{
				"msg": "error"
			})
		}			
	})	
});
// 登录接口
router.post("/selectuser", function(req, res) {
	var username = req.body.username;
	var password = req.body.password;
	var sql = "select * from user where username=?";
	var arr = [username];
	user.select(sql, arr, function(result) {
		if (result.length > 0) {
			res.json(200, result); // {username:"",password:""}
		}else {
			res.json(200, {
				"msg": "暂未注册"
			})
		}
	})
});
//修改接口
router.post("/updateuser", function(req, res) {
	var id = req.body.id;
	var password = req.body.password;
	var sql = "update user set password=? where id=?";
	var arr = [password,id];
	user.update(sql, arr, function(result) {
		if(result) {
			res.json(200, {
				"msg": "修改成功,请重新登录!"
			})
		}else {
			res.json(200,{
				"msg": "error"
			})
		}
	})
});
module.exports = router;